package concurrent;

import lombok.SneakyThrows;

import java.util.Random;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author Summerday
 */
public class TestSync {

    public static void main (String[] args) {
        SynchronousQueue<Integer> queue = new SynchronousQueue<>(true);
        Producer producer = new Producer(queue);
        Customer customer = new Customer(queue);
        producer.start();
        customer.start();
    }
}

class Producer extends Thread{
    SynchronousQueue<Integer> queue;
    Producer(SynchronousQueue<Integer> queue){
        this.queue = queue;
    }

    @SneakyThrows
    @Override
    public void run () {

        while(true){
            int product = new Random().nextInt(500);
            System.out.println("生产产品, id : " + product);
            System.out.println("等待3s后给消费者消费...");
            TimeUnit.SECONDS.sleep(3);
            queue.put(product);
            TimeUnit.MILLISECONDS.sleep(100);

        }
    }
}

class Customer extends Thread{
    SynchronousQueue<Integer> queue;
    Customer(SynchronousQueue<Integer> queue){
        this.queue = queue;
    }

    @SneakyThrows
    @Override
    public void run () {

        while(true){
            Integer product = queue.take();
            System.out.println("消费产品, id : " + product);
            System.out.println();
        }
    }
}
